import time,asyncio
from util.myredis import r
from datetime import datetime
import time,random
from db import db
import time
from util.myredis import r
from views.base import BaseHandler
import tornado
import json
import tornado.websocket,tornado.web

conndict = {}

class WebsockHandler(tornado.websocket.WebSocketHandler):
    #跨域支持
    def check_origin(self, origin):
        return True
    #建立连接
    def open(self):
        #参数获取
        id = int(self.get_argument('id'))
        #存储链接
        print('self',self)
        conndict[id] = self

    #接收消息
    def on_message(self,mes):
        print('mes',mes)

    def on_close(self):
        pass

class TTHandler(tornado.web.RequestHandler):
    def get(self):
        sql = """select min_temperature,max_temperature from num102.temperature"""
        res = db.findAll(sql)

        # for i in range(len(res)):
        #     print(res[i]['min_temperature'])
        #     print(res[i]['max_temperature'])

        min1 = res[0]['min_temperature']
        max1 = res[0]['max_temperature']

        min2 = res[1]['min_temperature']
        max2 = res[1]['max_temperature']

        min3 = res[2]['min_temperature']
        max3 = res[2]['max_temperature']

        min4 = res[3]['min_temperature']
        max4 = res[3]['max_temperature']
        while True:
            time.sleep(1)
            num1 = r.list_len('dapeng1')
            a = random.randint(0, num1 - 1)
            lst1 = r.list_getAll('dapeng1', 0, -1)

            n1 = float(lst1[a])
            #如果温度超过最大，或者小于最低温度，返回数据并发起警报
            if n1 < min1 or n1 > max1:
                print(n1)

            #大棚2
            num2 = r.list_len('dapeng2')
            a2 = random.randint(0, num2 - 1)
            lst2 = r.list_getAll('dapeng2', 0, -1)


            n2 = float(lst2[a2])
            # 如果温度超过最大，或者小于最低温度，返回数据并发起警报
            if n2 < min2 or n2 > max2:
                print(n2)

            #大棚3
            num3 = r.list_len('dapeng3')
            a3 = random.randint(0, num3 - 1)
            lst3 = r.list_getAll('dapeng3', 0, -1)

            n3 = float(lst3[a3])
            # 如果温度超过最大，或者小于最低温度，返回数据并发起警报
            if n3 < min3 or n3 > max3:
                print(n3)

            #大棚4
            num4 = r.list_len('dapeng4')
            a4 = random.randint(0, num4 - 1)
            lst4 = r.list_getAll('dapeng4', 0, -1)

            n4 = float(lst4[a4])
            # 如果温度超过最大，或者小于最低温度，返回数据并发起警报
            if n4 < min4 or n4 > max4:
                print(n4)

        # msg = res
        # id = int(self.get_query_argument("id"))
        # conndict[id].write_message(msg)



